package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/lib/pq"
)

const (
	host     = "localhost"
	port     = 5433
	user     = "postgres"
	password = "admin"
	dbname   = "DiscordClient"
)

// Take const values from environment variables
// and connect to the database using the postgres driver
func ConnectPostgresDB() *sql.DB {
	psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",
		host, port, user, password, dbname)
	db, err := sql.Open("postgres", psqlInfo)
	if err != nil {
		panic(err)
	}

	err = db.Ping()
	if err != nil {
		panic(err)
	}

	fmt.Println("Successfully connected!")
	return db
}

func main() {
	dbConnection := ConnectPostgresDB()
	result := GetAllServers(dbConnection)
	DeleteServer(&result, 1, dbConnection)
}

type Servers struct {
	id   int
	name string
}

func GetAllServers(db *sql.DB) []Servers {
	rows, err := db.Query("SELECT * FROM servers")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	serverList := []Servers{}

	for rows.Next() {
		p := Servers{}
		err := rows.Scan(&p.id, &p.name)
		if err != nil {
			fmt.Println(err)
			continue
		}
		serverList = append(serverList, p)
	}

	return serverList
}

func UpdateServers(db *sql.DB, id int, name string) {
	_, err := db.Exec("UPDATE servers SET name = $1 WHERE id = $2", name, id)
	if err != nil {
		log.Fatal(err)
	}
}

func AddServer(serverList *[]Servers, name string, db *sql.DB) *Servers {
	var id int
	db.QueryRow("INSERT INTO servers (name) VALUES ($1) returning id", name).Scan(&id)

	*serverList = append(*serverList, Servers{id, name})
	return &(*serverList)[len(*serverList)-1]
}

func DeleteServer(serverList *[]Servers, index int, db *sql.DB) {
	_, err := db.Exec("DELETE FROM servers WHERE id = $1", (*serverList)[index].id)
	if err != nil {
		log.Fatal(err)
	}
	*serverList = append((*serverList)[:index], (*serverList)[index+1:]...) // slice deletion
}
